787. Cheapest Flights Within K Stops - LeetCode Solution


Dynamic Programming Heap

Python Code:

class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:
        if src == dst: return 0
        
        d, seen = collections.defaultdict(list), collections.defaultdict(lambda: float('inf'))
        for u, v, p in flights:
            d[u] += [(v, p)]
    
        queue = [(src, -1, 0)]
        
        while queue:
            
            position, k, cost = queue.pop(0)
            
            if position == dst or k == K: 
                continue 
            for nei, p in d[position]:
                if cost + p >= seen[nei]:
                    continue
                else:
                    seen[nei] = cost+p
                    queue += [(nei, k+1, cost+p)]
                
        return seen[dst] if seen[dst] < float('inf') else -1
        


Comments

Submit
0 Comments
More Questions

Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship
Health of a person
Divisibility
A. Movement
Numbers in a matrix
Sequences
Split houses
Divisible
Three primes
Coprimes
Cost of balloons
One String No Trouble
Help Jarvis!
Lift queries
Goki and his breakup
Ali and Helping innocent people
Book of Potion making
Duration
Birthday Party
e-maze-in
Bricks Game
Char Sum
Two Strings
Anagrams
Prime Number
Lexical Sorting Reloaded
1514A - Perfectly Imperfect Array